//
//  SearchViewController.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/4/23.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "SearchViewController.h"
#import "CosMeticListTableViewCell.h"
#import "CommodityInFoViewController.h"
#import "InterFace.h"
#import "UIViewAdditions.h"
#import "AFNetworking.h"
#import "EncryptionData.h"
#import "ProductListModel.h"
#import "CosMeticListTableViewCell.h"
#import "GMDCircleLoader.h"


#import "Reachability.h"
#import "NetStatus.h"

@interface SearchViewController ()<UITextFieldDelegate>
{
    UITextField *_searchView;
    UITapGestureRecognizer *_tapGesture;
    UIButton *_searchImage ;
}
@property (nonatomic,strong) NSMutableArray *searchArray;
@end

@implementation SearchViewController

- (void)dealloc{
    [self.view removeGestureRecognizer:_tapGesture];//移除手势
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchArray = [NSMutableArray array];

    [self.navigationItem setHidesBackButton:YES];
    [self createSearchView];
    [self createTableView];

    
    //在self.view上添加一个单击手势
    _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    _tapGesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:_tapGesture];
}

#pragma -mark 创建搜索框
- (void)createSearchView{

        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
        
        UIButton *backBut = [UIButton buttonWithType:UIButtonTypeCustom];
           backBut.frame = CGRectMake(-25, -2, 85, 44);
        [backBut setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        [backBut addTarget:self action:@selector(clickBackBtn:) forControlEvents:UIControlEventTouchUpInside];
        //[navBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [view addSubview:backBut];

        //搜索框
        _searchView = [[UITextField alloc]initWithFrame:CGRectMake(backBut.right, 5, 200, 30)];
        _searchView.layer.masksToBounds = YES;
        _searchView.delegate = self;
        _searchView.layer.cornerRadius = 6/2;
        _searchView.textColor = [UIColor whiteColor];
    _searchView.backgroundColor = SearColor;

        _searchView.placeholder = @"商品名";
        [_searchView setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
        _searchView.font = [UIFont fontWithName:nil size:12];
        [view addSubview:_searchView];
        
        //搜索图片
        
        _searchImage = [[UIButton alloc]initWithFrame:CGRectMake(_searchView.right-30, 5, 30, 30)];
        _searchImage.backgroundColor = [UIColor clearColor];
        [_searchImage setImage:[UIImage imageNamed:@"订单--我的订单_03_02"] forState:UIControlStateNormal];
        [_searchImage addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:_searchImage];
    
        self.navigationItem.titleView = view;
    
}

#pragma -mark 返回按钮事件
- (void)clickBackBtn:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma -mark 创建TableView
- (void)createTableView{
    self.searchTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    [self.view addSubview:self.searchTableView];
    
    

}

#pragma -mark self.view单击手势事件
-(void)viewTapped:(UITapGestureRecognizer*)tap
{
   
    [_searchView resignFirstResponder];
    
}
#pragma -mark 点击搜索图标按钮事件
- (void)searchClick{
    
       [_searchView resignFirstResponder];
    if ([_searchView.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入要搜索的商品名" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    } else{
         [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
        
        //判断是否有网
        NetStatus *status = [[NetStatus alloc] init];
        if ([status.networkStatus isEqualToString:@"无网络"]) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        _searchImage.userInteractionEnabled = NO;
        [self getSearchConnectionRequest];
    }
}

#pragma -mark 导航最右按钮点击事件
- (void)rightBarButton{

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *iden = @"shoppingCell";
    CosMeticListTableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:iden];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:4];
    }
    [cell setMeticlistViewData:self.searchArray[indexPath.row]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed = YES;
    CommodityInFoViewController *commodityInfo = [[CommodityInFoViewController alloc] init];
    commodityInfo.productlistModel = self.searchArray[indexPath.row];
    commodityInfo.commVC = self;
    
    [self.navigationController pushViewController:commodityInfo animated:YES];

}

#pragma -mark 点击键盘return代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
  
    [textField resignFirstResponder];
    [self searchClick];
    
    return YES;
}

#pragma -mark 点击屏幕键盘收回方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
      [self.view endEditing:YES];
//    UITouch *touch = [touches anyObject];
//    
//    if (![touch.view isKindOfClass: [UITextField class]] || ![touch.view isKindOfClass: [UITextView class]]) {
//        
//        [self.view endEditing:YES];
//        
//    }
    
}

#pragma -mark 向服务器提交搜索请求
-(void)getSearchConnectionRequest{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
//    NSMutableArray *parameterArray = [[NSMutableArray alloc]init];
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameterDic = @{@"AgentID":agentId,@"Search":_searchView.text};
//    [parameterArray addObject:parameterDic];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameterDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    //EncryptionData *enctytion = [[EncryptionData alloc] init];
    NSString *str = [self encodeString:jsonString key:PasswordKey];

    NSDictionary *paramer = @{@"sign":str};
    __weak SearchViewController *searc = self;
    [manager POST:ProductListInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
          _searchImage.userInteractionEnabled = YES;
        
       // NSDictionary *dic =  [NSJSONSerialization  JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString *str = responseObject[@"sign"];
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        
        NSLog(@"返回搜索结果 ＝＝＝＝ %@",dataDic);
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            
            [searc.searchArray removeAllObjects];
            
            NSLog(@"返回搜索结果 ＝＝＝＝ %@",dataDic);
            NSArray *myDatArr =dataDic[@"data"];
            //
            for (int i = 0; i <[myDatArr count]; i++) {
                //
                NSDictionary *productDic = myDatArr[i];
                ProductListModel *model = [[ProductListModel alloc] init];
                [model setValuesForKeysWithDictionary:productDic];
                [searc.searchArray addObject:model];
            }
            [searc.searchTableView reloadData];
            
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
         _searchImage.userInteractionEnabled = YES;
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];
}

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}
@end
